package com.filter;

import com.service.userService;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class loginFilter implements Filter {
    private userService userService=new userService();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
          HttpServletRequest req=(HttpServletRequest) servletRequest;
          HttpServletResponse resp= (HttpServletResponse)servletResponse;
        Cookie[] cookies = req.getCookies();
        boolean isLoging=false;
        if(cookies==null||cookies.length==0){
            resp.sendRedirect("login.jsp");
            return;
        }else{
            for (int i = 0; i < cookies.length; i++) {
                if(cookies[i].getName().equals("loginUser")){
                    isLoging=true;
                    break;
                }
            }


        }
        if(isLoging){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }else{
            resp.sendRedirect("login.jsp");
        }




    }

    @Override
    public void destroy() {

    }
}
